import React, { useState, useEffect, useMemo } from 'react';
import { AutoComplete } from 'antd';
import { debounce } from 'lodash';
import PropTypes from 'prop-types';

function findLabel(options, value) {
  const item = options?.find((op) => op.value === value);
  return item ? item?.label : value;
}

/**
 * 除flag,其他参数为AutoComplete自有参数
 * @param flag {boolean} 为false时是输入拼音 为true为正常输入
 * @param value
 * @param options
 * @param onChange
 * @param placeholder
 * @param onSearch
 * @param handleSelect
 * @param style
 * @param children
 * @param allowClear
 * @param disabled
 * @returns {JSX.Element}
 */
const AutoCompleteC = ({ flag = true, value: originValue, options, onChange, placeholder, onSearch, onSelect: handleSelect, style, children, allowClear, disabled }) => {
  // 定义了state变量 newValue
  // 使用 setNewValue 方法更新newValue
  // 初始值是从父容器传入的 value
  // 如果初始值为唯一ID，则newValue值为对应的label，若不是唯一ID，则newValue是直接文本
  const [newValue, setNewValue] = useState(() => {
    return findLabel(options, originValue);
  });

  // 响应value或options值的变更，当变更时，更新newValue
  useEffect(() => {
    if (flag !== false) {
      setNewValue(findLabel(options, originValue));
    }
  }, [originValue, options]);
  // 当options变更时，重新更新newOptions
  const newOptions = useMemo(() => {
    return options?.map((op) => {
      const { value, label } = op;
      return {
        key: value,
        value: label,
      };
    });
  }, [options]);

  const throttleHandleChange = debounce(onChange, 20);

  const handleChange = (value) => {
    throttleHandleChange(value);
    setNewValue(value);
  };

  const onSelect = (val, option) => {
    throttleHandleChange(option.key);
    if (typeof handleSelect === 'function') {
      handleSelect(option.key);
    }
  };

  return (
    <AutoComplete
      allowClear={allowClear}
      style={style}
      options={
        options && options.length > 0
          ? newOptions
          : options === undefined
          ? [{ label: <span disabled={true}>正在加载中....</span> }]
          : [{ label: <span disabled={true}>无匹配的结果</span> }]
      }
      // options={newOptions}
      placeholder={placeholder}
      value={newValue}
      disabled={disabled}
      onChange={handleChange}
      onSelect={onSelect}
      // filterOption={(inputValue, option) => option.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
      onSearch={onSearch}
    >
      {children}
    </AutoComplete>
  );
};
AutoCompleteC.propsTypes = {
  flag: PropTypes.bool.isRequired, //  为false时是输入拼音 为true为正常输入
};
export default AutoCompleteC;
